﻿using AutoMapper;
using B.S.Filtration.Domain;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Read.Api.Application.Command.VendorItemsCommand;
using B.S.Filtration.Read.Api.Dto;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using NPOI.Util;
using SqlSugar;

namespace B.S.Filtration.Read.Api.Application.CommandHander.VendorItemsCommandHander
{
    public class QueryVendorItemsCommandHander : IRequestHandler<QueryVendorItemsCommand, APIPaging<List<VendorItemsDtos>>>
    {
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public QueryVendorItemsCommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        public Task<APIPaging<List<VendorItemsDtos>>> Handle(QueryVendorItemsCommand request, CancellationToken cancellationToken)
        {
            APIPaging<List<VendorItemsDtos>> result = new APIPaging<List<VendorItemsDtos>>();

            var item = db.Queryable<VendorItems>()
                       .InnerJoin<Vendor>((a, b) => a.VendorId == b.VendorId)
                       .Where((a, b) => a.Del == false && a.VendorId == request.VendorId)
                       .Select((a, b) => new VendorItemsDtos
                       {
                           VendorItemsId = a.VendorItemsId,
                           VendorId = b.VendorId,
                           ItemCode = a.ItemCode,
                           ItemName = a.ItemName,
                           specificationModel = a.specificationModel,
                           unit = a.unit,
                           itemCategory = a.itemCategory,
                           itemAttribute = a.itemAttribute,
                           itemType = a.itemType,
                           Del = a.Del,



                           SupplierCode = b.SupplierCode,
                           SystemCode = b.SystemCode,
                           CompanyName = b.CompanyName,
                           SupplierLevel = b.SupplierLevel,
                           SupplierCategory = b.SupplierCategory,
                           PersonnelScale = b.PersonnelScale,
                           CompanyAddress = b.CompanyAddress,
                           RegisteredAddress = b.RegisteredAddress,
                           CreditCode = b.CreditCode,
                           Remark = b.Remark,
                       });

            result.TotalCount = item.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            item = item.OrderByDescending(a => a.VendorId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            result.code = APIResultCode.success;
            result.msg = "查询成功";
            result.data = mapper.Map<List<VendorItemsDtos>>(item.ToList());

            return Task.FromResult(result);
        }
    }
}
